package com.example.broadcastapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter; /*定义过滤器*/
    private TimeChangeReceivers timeChangeReceivers;
    private NetworkChangeReceiver networkChangeReceivers;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /*监听时间变化*/
        /*timeChangeReceivers = new TimeChangeReceivers();
        intentFilter = new IntentFilter("android.intent.action.TIME_TICK"); *//*每过一分钟出现弹窗*//*
        registerReceiver(timeChangeReceivers, intentFilter); *//*动态注册广播*/

        /*监听网络状态*/
        networkChangeReceivers = new NetworkChangeReceiver();
        intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(networkChangeReceivers, intentFilter);

    }

    /*解除注册*/
    @Override
    protected void onDestroy() {
        super.onDestroy();
        /*
        unregisterReceiver(timeChangeReceivers);
        */

        unregisterReceiver(networkChangeReceivers);
    }

    /*实例化自定义的广播接收器*/
    class TimeChangeReceivers extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Time Changes!", Toast.LENGTH_SHORT).show();
        }
    }

    class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "Network Changes!", Toast.LENGTH_SHORT).show();
        }
    }
}